/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 */

import process from 'process';
import util from 'util';

import { BuildStatus, OutputType } from '../../base/common/daemon-protocol/common-enum.js';
import { BuildStatusMessage, Message, OutputMessage } from '../../base/common/daemon-protocol/message.js';
import { HvigorLogger } from '../../base/log/hvigor-log.js';

const log = HvigorLogger.getLogger('client-event-handler');

export function printLog(output: OutputMessage): void {
  if (!output || !output.type || !output.text) {
    handleServerMsgError(log, output);
    return;
  }
  if (output.type === OutputType.STDOUT) {
    process.stdout.write(output.text, output.encoding);
  }
  if (output.type === OutputType.STDERR) {
    process.stderr.write(output.text, output.encoding);
  }
}

export function handleBuildStatus(msg: BuildStatusMessage) {
  if (!msg || !msg.status) {
    handleServerMsgError(log, msg);
    return;
  }

  function exitWithLog(logContent: string) {
    log.debug(logContent);
    process.exitCode = msg.exitCode ?? -1;
    process.exit();
  }

  if (msg.reason) {
    log.error(msg.reason);
  }

  if (msg.status === BuildStatus.FINISH) {
    exitWithLog('The build request was finished');
  }

  if (msg.status === BuildStatus.REJECT) {
    exitWithLog('The build request was rejected.');
  }

  if (msg.status === BuildStatus.CLOSE) {
    exitWithLog('The build request was closed.');
  }
}

export function handleWatchBuildResult(msg: any) {
  log.debug(msg);
}

export function handleWatchLog(msg: any) {
  log.info(msg);
}

export function handleServerMsgError(log: HvigorLogger, msg: Message) {
  log.warn('Received server exception type information.');
  log.warn(`receive server message:${util.format(msg)}`);
}
